package com.itheima.health.service.impl;

import com.itheima.health.pojo.Permission;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.RoleVO;
import com.itheima.health.vo.UserVO;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("username = " + username);
        UserVO userVO = userService.findUserDetailsByUsername(username);
        if (userVO == null) {
            return null;
        }

        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        List<RoleVO> roles = userVO.getRoles();
        for (RoleVO role : roles) {

            grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));

            List<Permission> permissionSet = role.getPermissionList();
            for (Permission permission : permissionSet) {

                grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));


            }
        }
        System.out.println("userVO = " + userVO);
        return new User(username, userVO.getPassword(), grantedAuthorityList);
    }
}
